defmodule EliPhxPlayWeb.Components.DashboardRight.GroupsComponent do
  use EliPhxPlayWeb, :live_component
  alias EliPhxPlay.Context.Accounts
  alias EliPhxPlay.Context.UserRelationship
  alias EliPhxPlay.Context.Groups
  alias EliPhxPlay.Context.GroupMembers

  alias Phoenix.PubSub



  def mount(socket) do
    {:ok, assign(socket,
      show_create_group_modal: false,
      group_name: "",
      group_description: "",
      selected_members: [],
      search_term: "",
      search_results: [],
      show_notification: false,
      notification_type: nil,
      notification_message: "",
      notification_timer: nil,
      show_group_info_modal: false,
      selected_group: nil,
      show_join_group_modal: false,
      search_term_join: "",
      group_search_results: []
    )}
  end




  def render(assigns) do
  ~H"""
  <div class="h-full bg-white flex flex-col">

    <%= render_groups_header(assigns) %>

    <!-- 群聊列表 - 可滚动区域 -->
    <div class="flex-1 overflow-y-auto">
      <%= if @groups && length(@groups) > 0 do %>
        <div class="divide-y divide-gray-200">
          <%= for group <- @groups do %>
            <div class="p-4 hover:bg-gray-50 transition-colors duration-200">
              <div class="flex items-center justify-between">
                <div class="flex items-center space-x-4">
                  <!-- 群聊头像 -->
                  <div class="flex-shrink-0">
                    <%= if group.group_avatar do %>
                      <img class="h-12 w-12 rounded-full object-cover" src={group.group_avatar} alt={group.name}>
                    <% else %>
                      <div class="h-12 w-12 rounded-full bg-gradient-to-r from-green-500 to-blue-600 flex items-center justify-center">
                        <span class="text-lg font-medium text-white font-bold">
                          <%= String.first(group.group_name || "群") %>
                        </span>
                      </div>
                    <% end %>
                  </div>

                  <!-- 群聊信息 -->
                  <div class="flex-1 min-w-0">
                    <div class="flex items-center space-x-2">
                      <p class="text-sm font-medium text-gray-900 truncate">
                        <%= group.group_name %>
                      </p>
                      <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                        <%= 0 %>人
                      </span>
                    </div>
                    <p class="text-sm text-gray-500 truncate">
                      <%= group.group_description || "暂无群描述" %>
                    </p>
                    <%!-- <%= if group.last_message do %>
                      <p class="text-xs text-gray-400 truncate mt-1">
                        最新：<%= group.last_message %>
                      </p>
                    <% end %> --%>
                  </div>
                </div>

                <!-- 操作按钮 -->
                <div class="flex items-center space-x-2">
                  <button
                    phx-click="enter_group_chat"
                    phx-value-group-id={group.group_id}
                    phx-target={@myself}
                    class="inline-flex items-center px-3 py-1.5 border border-transparent text-xs font-medium rounded-md text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 transition-colors duration-200"
                  >
                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 4v-4z"></path>
                    </svg>
                    进入
                  </button>

                  <button
                    phx-click="show_group_info"
                    phx-value-group-id={group.group_id}
                    phx-target={@myself}
                    class="inline-flex items-center px-3 py-1.5 border border-gray-300 text-xs font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors duration-200"
                  >
                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                    </svg>
                    信息
                  </button>
                </div>
              </div>
            </div>
          <% end %>
        </div>
      <% else %>
        <div class="flex flex-col items-center justify-center h-full text-gray-500 p-8">
          <svg class="w-16 h-16 mb-4 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 4v-4z"></path>
          </svg>
          <p class="text-lg mb-2 text-gray-600">还没有群聊</p>
          <p class="text-sm text-gray-400">点击上方"创建群聊"开始建立群组吧！</p>
        </div>
      <% end %>
    </div>

  </div>
  """
  end


    defp render_groups_header(assigns) do
    ~H"""
    <!-- 头部区域 -->
    <div class="bg-white border-b border-gray-200 px-6 py-4 flex-shrink-0">
      <div class="flex items-center justify-between">
        <div class="flex items-center space-x-3">
          <h1 class="text-xl font-semibold text-gray-900">群聊</h1>
          <%= if @groups && length(@groups) > 0 do %>
            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
              <%= length(@groups) %>个群
            </span>
          <% end %>
        </div>

        <div class="flex items-center space-x-2">
          <button
            phx-click="show_join_group_modal"
            phx-target={@myself}
            class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-all duration-200"
          >
            <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
            </svg>
            加入群聊
          </button>

          <button
            phx-click="show_create_group_modal"
            phx-target={@myself}
            class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 transition-all duration-200"
          >
            <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
            </svg>
            创建群聊
          </button>
        </div>
      </div>
    </div>

    <!-- 创建群聊模态框 -->
    <%= if @show_create_group_modal do %>
      <div class="fixed inset-0 z-50 overflow-y-auto">
        <!-- 背景遮罩 -->
        <div
          class="fixed inset-0 bg-black bg-opacity-50 transition-opacity"
          phx-click="close_create_group_modal"
          phx-target={@myself}
        ></div>

        <!-- Modal 内容 -->
        <div class="flex min-h-full items-center justify-center p-4">
          <div class="relative bg-white rounded-lg shadow-xl max-w-md w-full">
            <!-- Modal 头部 -->
            <div class="flex items-center justify-between p-6 border-b">
              <h3 class="text-lg font-semibold text-gray-900">创建群聊</h3>
              <button
                phx-click="close_create_group_modal"
                phx-target={@myself}
                class="text-gray-400 hover:text-gray-600"
              >
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                </svg>
              </button>
            </div>

            <!-- Modal 内容 -->
            <div class="p-6">
              <form phx-submit="create_group" phx-target={@myself}>
                <div class="mb-4">
                  <label class="block text-sm font-medium text-gray-700 mb-2">
                    群聊名称
                  </label>
                  <input
                    type="text"
                    name="group_name"
                    phx-target={@myself}
                    value={@group_name || ""}
                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
                    placeholder="请输入群聊名称"
                    required
                  />
                </div>

                <div class="mb-6">
                  <label class="block text-sm font-medium text-gray-700 mb-2">
                    群聊描述（可选）
                  </label>
                  <textarea
                    name="group_description"
                    phx-target={@myself}
                    value={@group_description || ""}
                    rows="3"
                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
                    placeholder="请输入群聊描述"
                  ></textarea>
                </div>

                <div class="flex justify-end gap-3">
                  <button
                    type="button"
                    phx-click="close_create_group_modal"
                    phx-target={@myself}
                    class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-md transition-colors"
                  >
                    取消
                  </button>
                  <button
                    type="submit"
                    class="px-4 py-2 text-sm font-medium text-white bg-green-600 hover:bg-green-700 rounded-md transition-colors"
                  >
                    创建群聊
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    <% end %>

    <!-- 加入群聊模态框 -->
    <%= if @show_join_group_modal do %>
      <div class="fixed inset-0 z-50 overflow-y-auto">
        <!-- 背景遮罩 -->
        <div
          class="fixed inset-0 bg-black bg-opacity-50 transition-opacity"
          phx-click="close_join_group_modal"
          phx-target={@myself}
        ></div>

        <!-- Modal 内容 -->
        <div class="flex min-h-full items-center justify-center p-4">
          <div class="relative bg-white rounded-lg shadow-xl max-w-md w-full">
            <!-- Modal 头部 -->
            <div class="flex items-center justify-between p-6 border-b">
              <h3 class="text-lg font-semibold text-gray-900">加入群聊</h3>
              <button
                phx-click="close_join_group_modal"
                phx-target={@myself}
                class="text-gray-400 hover:text-gray-600"
              >
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                </svg>
              </button>
            </div>

            <!-- Modal 内容 -->
            <div class="p-6">
              <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-2">
                  群聊名称或群号
                </label>
                <input
                  type="text"
                  name="group_identifier"
                  phx-keyup="search_groups"
                  phx-debounce="300"
                  phx-target={@myself}
                  value={@search_term_join || ""}
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="请输入群聊名称或群号"
                  required
                />

                <!-- 搜索结果显示 -->
                <%= if @group_search_results && length(@group_search_results) > 0 do %>
                  <div class="mt-2 bg-white border border-gray-300 rounded-md shadow-lg max-h-48 overflow-y-auto">
                    <%= for group <- @group_search_results do %>
                      <div class="px-4 py-2 hover:bg-gray-50 border-b last:border-b-0 flex items-center justify-between">
                        <div class="flex-1">
                          <div class="font-medium"><%= group.group_name %></div>
                          <div class="text-sm text-gray-500">群号：<%= group.group_code %></div>
                          <%= if group.group_description && group.group_description != "" do %>
                            <div class="text-xs text-gray-400 truncate"><%= group.group_description %></div>
                          <% end %>
                        </div>
                        <button
                          class="ml-3 px-3 py-1 bg-blue-600 hover:bg-blue-700 text-white text-sm rounded-md transition-colors"
                          phx-click="join_group"
                          phx-value-group-id={group.group_id}
                          phx-target={@myself}
                        >
                          加入群聊
                        </button>
                      </div>
                    <% end %>
                  </div>
                <% end %>
              </div>
            </div>
          </div>
        </div>
      </div>
    <% end %>


    <!-- 通知弹窗 -->
    <%= if @show_notification do %>
      <div
        class="fixed inset-0 z-50 flex items-center justify-center pointer-events-none"
        phx-click="hide_notification"
        phx-target={@myself}
      >
        <div class={"px-6 py-4 rounded-lg shadow-lg text-white font-medium pointer-events-auto transform transition-all duration-300 cursor-pointer #{if @notification_type == :success, do: "bg-green-500", else: "bg-red-500"}"}>
          <%= @notification_message %>
          <button
            class="ml-2 text-white hover:text-gray-200"
            phx-click="hide_notification"
            phx-target={@myself}
          >
            ×
          </button>
        </div>
      </div>
    <% end %>

    """
    end

    # 显示创建群聊模态框
    def handle_event("show_create_group_modal", _params, socket) do
      {:noreply, assign(socket, show_create_group_modal: true)}
    end

    # 关闭创建群聊模态框
    def handle_event("close_create_group_modal", _params, socket) do
      {:noreply, assign(socket,
        show_create_group_modal: false,
        group_name: "",
        group_description: ""
      )}
    end

    # 处理创建群聊表单提交
    def handle_event("create_group", %{"group_name" => group_name, "group_description" => group_description}, socket) do
      current_user_id = socket.assigns.user_id

      # 构建群聊属性
      group_attrs = %{
        group_name: String.trim(group_name),
        group_description: String.trim(group_description),
        owner_id: current_user_id
      }

      # 调用创建群聊的Context函数（需要您实现）
      case EliPhxPlay.Context.Groups.create_group(group_attrs) do
        {:ok, group} ->
          # 通知父组件更新群聊列表
          send(self(), {:update_groups})

          {:noreply,
            socket
            |> assign(
              show_create_group_modal: false,
              group_name: "",
              group_description: ""
            )
            |> show_notification(:success, "群聊 \"#{group.group_name}\" 创建成功！")}

        {:error, changeset} ->
          # 处理创建失败
          error_message = case changeset.errors do
            errors when is_list(errors) ->
              cond do
                Keyword.has_key?(errors, :group_name) ->
                  "群聊名称不能为空或格式不正确"
                true ->
                  "创建群聊失败，请重试"
              end
            _ ->
              "创建群聊失败，请重试"
          end

          {:noreply, show_notification(socket, :error, error_message)}
      end
    end

    # 进入群聊
    def handle_event("enter_group_chat", %{"group-id" => group_id}, socket) do
      # 处理进入群聊逻辑
      send(self(), {:enter_group_chat, group_id})
      {:noreply, socket}
    end

    # 显示群聊信息
    def handle_event("show_group_info", %{"group-id" => group_id}, socket) do
      # 显示群聊详细信息
      group = Enum.find(socket.assigns.groups || [], &(&1.id == String.to_integer(group_id)))
      {:noreply, assign(socket, show_group_info_modal: true, selected_group: group)}
    end

    # 隐藏通知
    def handle_event("hide_notification", _params, socket) do
      if socket.assigns[:notification_timer] do
        Process.cancel_timer(socket.assigns.notification_timer)
      end

      {:noreply, assign(socket,
        show_notification: false,
        notification_timer: nil
      )}
    end

    # 显示通知的辅助函数
    defp show_notification(socket, type, message) do
      assign(socket,
        show_notification: true,
        notification_type: type,
        notification_message: message
      )
    end

    # 处理定时器自动隐藏通知
    def handle_info(:hide_notification, socket) do
      {:noreply, assign(socket,
        show_notification: false,
        notification_timer: nil
      )}
    end

    # 显示加入群聊模态框
    def handle_event("show_join_group_modal", _params, socket) do
      {:noreply, assign(socket, show_join_group_modal: true)}
    end

    # 关闭加入群聊模态框
    def handle_event("close_join_group_modal", _params, socket) do
      {:noreply, assign(socket,
        show_join_group_modal: false,
        search_term_join: "",
        group_search_results: []
      )}
    end

    # 搜索群聊
    def handle_event("search_groups", %{"value" => search_term_join}, socket) do
      search_term_join = String.trim(search_term_join)

      if String.length(search_term_join) >= 2 do
        # 调用Groups Context的搜索函数
        results = Groups.search_groups(search_term_join)
        {:noreply, assign(socket, search_term_join: search_term_join, group_search_results: results)}
      else
        {:noreply, assign(socket, search_term_join: search_term_join, group_search_results: [])}
      end
    end


    # 加入群聊
    def handle_event("join_group", %{"group-id" => group_id}, socket) do
      current_user_id = socket.assigns.user_id

      case GroupMembers.create_group_member_role_member(group_id, current_user_id) do
        {:ok, _group_member} ->
          # 成功加入群聊
          send(self(), {:update_groups})

          # 获取群聊信息用于显示通知
          group_info = Enum.find(socket.assigns.group_search_results || [], &(&1.group_id == group_id))
          group_name = if group_info, do: group_info.group_name, else: "该群聊"

          {:noreply,
            socket
            |> assign(
              show_join_group_modal: false,
              search_term_join: "",
              group_search_results: []
            )
            |> show_notification(:success, "成功加入群聊 \"#{group_name}\"")}

        {:error, "用户已经是群成员"} ->
          # 用户已经是群成员
          {:noreply, show_notification(socket, :error, "您已经是该群的成员")}

        {:error, _changeset} ->
          # 其他数据库错误
          {:noreply, show_notification(socket, :error, "加入群聊失败，请稍后重试")}
      end
    end




end
